<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/7/20
 * Time: 22:51
 */
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
use Laravel\Lumen\Routing\Controller as BaseController;

class UserController extends Controller
{
    private $salt;

    public function __construct()
    {
        $this->salt = "userloginregister";
    }

    public function login(Request $request)
    {
        $res = [
            'status'=>0
        ];
        if ($request->has('username') && $request->has('password')) {
            $user = User:: where("username", "=", $request->input('username'))
                ->where("password", "=", sha1($this->salt . $request->input('password')))
                ->first();

            if ($user) {
                $token = str_random(60);
                $user->api_token = $token;
                $user->save();
                $res['api_token'] = $user->api_token;
            } else {
                $res['status'] = 1;
                $res['description'] = "用户名或密码不正确，登录失败！";
            }
        } else {
            $res['status'] = 1;
            $res['description'] = "用户名或密码不正确，登录失败！";
        }
        echo json_encode( $res );
    }

    public function register(Request $request){
        if ($request->has('username') && $request->has('password') && $request->has('email')) {
            $user = new User;
            $user->username=$request->input('username');
            $user->password=sha1($this->salt.$request->input('password'));
            $user->email=$request->input('email');
            $user->api_token=str_random(60);
            if($user->save()){
                return "用户注册成功！";
            } else {
                return "用户注册失败！";
            }
        } else {
            return "请输入完整用户信息！";
        }
    }

    public function info(){
        return Auth::user();
    }
}